package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qk.common.PageResult;
import com.qk.common.contant.BusinessStatusContant;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.dto.business.BusinessFollowDTO;
import com.qk.dto.business.BusinessListDTO;
import com.qk.dto.business.BusinessPoolListDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;
import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.BusinessMapper;
import com.qk.management.mapper.BusinessTrackRecordMapper;
import com.qk.management.mapper.CustomerMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessByIdVO;
import com.qk.vo.business.BusinessListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;

    //公海池列表查询
    @Override
    public PageResult<Business> getPoolList(BusinessPoolListDTO dto) {
        IPage<Business> pages = new Page<>(dto.getPage(), dto.getPageSize());
        Business business = BeanUtil.copyProperties(dto, Business.class);
        business.setId(dto.getBusinessId());

        IPage<Business> businessIPage = this.baseMapper.selectPage(pages, Wrappers.lambdaQuery(Business.class)
                .eq(Business::getStatus, BusinessStatusContant.RECOVERY)
                .eq(ObjectUtil.isNotEmpty(dto.getBusinessId()), Business::getId, dto.getBusinessId())
                .eq(ObjectUtil.isNotEmpty(dto.getPhone()), Business::getPhone, dto.getPhone())
                .eq(ObjectUtil.isNotEmpty(dto.getName()), Business::getName, dto.getName())
                .eq(ObjectUtil.isNotEmpty(dto.getSubject()), Business::getSubject, dto.getSubject()));


        return PageResult.<Business>builder()
                .total(Long.valueOf(businessIPage.getTotal()).intValue())
                .rows(businessIPage.getRecords())
                .build();
    }


    //跟进商机
    @Override
    public void followBusiness(BusinessFollowDTO businessFollowDTO) {
        //判断商机状态是否为待分配,才进行修改
        Integer status = this.baseMapper.selectById(businessFollowDTO.getId()).getStatus();
        if (ObjectUtil.isNotEmpty(status) && status.equals(BusinessStatusContant.WAIT_FOLLOW_UP)){
            Business business = businessMapper.selectById(businessFollowDTO.getId());
            business.setStatus(BusinessStatusContant.FOLLOW_UP);
            businessMapper.updateById(business);
        }

        //一、把商机数据插入到business_track_record表
        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(businessFollowDTO, BusinessTrackRecord.class);
        businessTrackRecord.setId(null);
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        businessTrackRecord.setBusinessId(businessFollowDTO.getId());
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecordMapper.insert(businessTrackRecord);
    }


    @Override
    public BusinessByIdVO getBusinessById(Integer id) {
        //先查询商机表中对应id的数据,生成一个business
        Business business = this.baseMapper.selectById(id);
        //再把business数据转换成businessListVO
        BusinessByIdVO businessByIdVO = BeanUtil.copyProperties(business, BusinessByIdVO.class);
        //此时其他数据都有值了,还剩下要查询的trackRecords数据
        //再查询trackRecords数据生成一个businessByIdTrackRecordsVO
        List<BusinessTrackRecord> businessTrackRecords = this.businessTrackRecordMapper.selectList(
                new LambdaQueryWrapper<>(BusinessTrackRecord.class)
                        .eq(BusinessTrackRecord::getBusinessId, id)
        );
        //根据userId查询用户名称aassignName
        //再判断businessTrackRecords中userId是否为空
        if (ObjectUtil.isNotEmpty(businessTrackRecords)) {
            //将List<BusinessTrackRecord>变为List<BusinessByIdVO.BusinessByIdTrackRecordsVO>
            List<BusinessByIdVO.BusinessByIdTrackRecordsVO> businessByIdTrackRecordsVOS = new ArrayList<>();
            for (BusinessTrackRecord businessTrackRecord : businessTrackRecords) {
                BusinessByIdVO.BusinessByIdTrackRecordsVO businessByIdTrackRecordsVO = BeanUtil.copyProperties(businessTrackRecord, BusinessByIdVO.BusinessByIdTrackRecordsVO.class);
                businessByIdTrackRecordsVO.setAssignName(userMapper.selectById(businessTrackRecord.getUserId()).getUsername());
                businessByIdTrackRecordsVOS.add(businessByIdTrackRecordsVO);
            }
            //最后添加到businessListVO的trackRecords中
            businessByIdVO.setTrackRecords(businessByIdTrackRecordsVOS);
        }


        return businessByIdVO;
    }


    //转商机
    @Override
    public void toCustomer(Integer id) {
        //更改商机表中对应id的status
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusContant.TO_CUSTOMER);
        this.businessMapper.updateById(business);

        //添加对应数据到客户表中
        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customerMapper.insert(customer);
    }


    //踢回公海
    @Override
    public void backToPool(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusContant.RECOVERY);
        this.businessMapper.updateById(business);
    }


    //分配商机
    @Override
    public void assignBusinessUser(Integer businessId, Integer userId) {
        Business business = new Business();
        business.setId(businessId);
        business.setUserId(userId);
        business.setStatus(BusinessStatusContant.WAIT_FOLLOW_UP);
        business.setUpdateTime(LocalDateTime.now());
        this.businessMapper.updateById(business);
    }


    @Override
    public void addBusiness(Business business) {
        business.setStatus(BusinessStatusContant.WAIT_ALLOCATION);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.businessMapper.insert(business);
    }


    //分页查询
    @Override
    public PageResult<BusinessListVO> getBusinessList(BusinessListDTO businessListDTO) {
        // 分页查询:
        //   检查assignName是否为空,不为空时查询用户,为空时直接根据条件查询
        //   根据assignName查询用户userId
        //   将BusinessListDTO强转为Business
        //   查询所有符合条件的Business
        //   再将Business强转为BusinessListVO

        // 分页设置
        IPage<Business> pages = new Page<>(businessListDTO.getPage(), businessListDTO.getPageSize());

        // 动态查询条件构建
        LambdaQueryWrapper<Business> wrapper = Wrappers.lambdaQuery(Business.class);

        // 只有当参数不为空时才添加查询条件
        if (ObjectUtil.isNotEmpty(businessListDTO.getName())) {
            wrapper.eq(Business::getName, businessListDTO.getName());
        }
        if (ObjectUtil.isNotEmpty(businessListDTO.getPhone())) {
            wrapper.eq(Business::getPhone, businessListDTO.getPhone());
        }
        if (businessListDTO.getStatus() != null) {
            wrapper.eq(Business::getStatus, businessListDTO.getStatus());
        }

        // 处理 assignName 查询条件
        if (ObjectUtil.isNotEmpty(businessListDTO.getAssignName())) {
            User user = userMapper.selectByUsername(businessListDTO.getAssignName());
            if (user != null) {
                wrapper.eq(Business::getUserId, user.getId());
            } else {
                // 如果用户不存在，返回空结果
                return PageResult.<BusinessListVO>builder()
                        .total(0)
                        .rows(new ArrayList<>())
                        .build();
            }
        }

        // 执行查询
        IPage<Business> businesses = this.baseMapper.selectPage(pages, wrapper);

        // 转换结果
        List<BusinessListVO> businessListVO = new ArrayList<>();
        for (Business record : businesses.getRecords()) {
            BusinessListVO vo = BeanUtil.copyProperties(record, BusinessListVO.class);
            vo.setAssignName(userMapper.selectById(record.getUserId()).getName());
            businessListVO.add(vo);
        }

        return PageResult.<BusinessListVO>builder()
                .total(Long.valueOf(businesses.getTotal()).intValue())
                .rows(businessListVO)
                .build();
    }
}
